import axios from 'axios'
import querystring from 'querystring'
import { Loading } from 'element-plus';

const errorHandle = (status, info) => {
    switch (status) {
        case 400:
            console.log("语义错误");
            break;
        case 401:
            console.log("服务器认证失败");
            break;
        case 403:
            console.log("服务器拒绝访问");
            break;
        case 404:
            console.log("后台服务有异常或接口不存在!");
            break;
        case 500:
            console.log("服务器遇到意外");
            break;
        case 502:
            console.log("服务器无响应");
            break;
        default:
            console.log(info);
            break;
    }
}

axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded";

const instance = axios.create({
    // baseURL:'http://localhost:9001',  //baseURL会在发送请求的时候拼接在url参数前面
    timeout: 900000,
})

//发送数据之前的拦截器
instance.interceptors.request.use(
    config => {
        // if (config.responseType != null) { //这里的条件可以自行更改成自己需要的条件
        //     console.log("显示loading");
      
        //     loadingInstance = Loading.service({
        //       lock: true, //lock的修改符--默认是false
        //       text: "拼命加载中...", //显示在加载图标下方的加载文案
        //       spinner: "el-icon-loading", //自定义加载图标类名
        //       background: "rgba(0, 0, 0, 0.7)", //遮罩层颜色
        //     });
        //   }

        if (config.method === 'post' && config.data instanceof File) {
            config.headers['Content-Type'] = 'multipart/form-data';
            const formData = new FormData();
            formData.append('excelFile', config.data);
            config.data = formData;
        }
        else if (config.method === "post" && config.data instanceof Object) {
            config.headers["Content-Type"] = "application/json;charset=UTF-8";
            //config.data = querystring.stringify(config.data)
            config.data = JSON.stringify(config.data)
        }
        return config;
    },
    error => {
        return Promise.reject(error)
    }
)

// //获取数据之前的拦截器
instance.interceptors.response.use(
    response => {
        return response.status === 200 ? Promise.resolve(response) : Promise.reject(response)
    },
    error => {
        const { response } = error;
        //错误信息处理
        errorHandle(response.status, response.info)
    }
)


export default instance;